<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 销售接口
 */
class Sale extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 提现
     */
    public function withdraw()
    {
        $money = $this->request->post('money');
        if (!$money) {
            $this->error("参数错误");
        }
        $user = \app\api\model\User::get($this->auth->id);
        if ($user->money < $money) {
            $this->error("余额不足");
        }
        // if($money > 200){
        //     $this->error("提现金额不能大于200");
        // }
        if($money < 0.1){
            $this->error("提现金额不能小于0.1");
        }
        $withdraw = new \app\api\model\WithdrawOrder();
        if($withdraw->where('user_id',$user->id)->where('status','=',10)->count('id')){
            $this->error("您有提现申请正在处理中,请等待处理完成");
        }

        $withdraw_day = config('site.common_discount') ?? 0;
        if($withdraw_day > 0){
            $withdrawInfo = $withdraw->where('user_id',$user->id)->where('status','in',[10,20])->order('createtime desc')->find();
            if($withdrawInfo && strtotime($withdrawInfo->createtime) + $withdraw_day*86400 > time()){
                $this->error("下次可提现日期:".date('Y-m-d H:i',strtotime($withdrawInfo->createtime) + $withdraw_day*86400));
            }
        }

        $out_bill_no = createOrdersn($user->id,'T');
        $withdraw->user_id = $user->id;
        $withdraw->money = $money;
        $withdraw->out_bill_no = $out_bill_no;
        $withdraw->status = 0;
        $withdraw->save();

        $request = request();
        $notifyurl =  $request->root(true) . '/api/notifyx/notifyxOrderTransfer/paytype/wechat';
        $result = \addons\epay\library\Service::submitTransfer([
            'out_bill_no'=>$out_bill_no,
            'transfer_scene_id'=>"1005",
            'openid'=>$user->openid,
            'user_name'=>$user->nickname,
            'transfer_amount'=>$money*100,
            'transfer_remark'=>'余额提现',
            'notify_url'=>$notifyurl,
            'transfer_scene_report_infos'=>[
                [
                    'info_type'=>'岗位类型',
                    'info_content'=>'销售人员'
                ],
                [
                    'info_type'=>'报酬说明',
                    'info_content'=>'项目分佣余额提现'
                ]
            ]

        ],'wechat');


        if(isset($result['state']) && $result['state']=='WAIT_USER_CONFIRM'){
            Db::startTrans();
            $withdraw->status = 10;
            $withdraw->remark = $result['state'];
            $withdraw->save();

            // $user->setUpdateMoneyParams([
            //     'memo'=>'提现申请成功',
            //     'title'=>'提现申请成功',
            //     'datatype'=>20
            // ]);
            // $user->money = $user->money - $money;
            // $res = $user->save();
            // if(!$res){
            //     Db::rollback();
            //     $this->error("提现申请失败");
            // }
            $wechat = get_addon_config('epay')['wechat'];
            Db::commit();
            $this->success("",[
                'package'=>$result['package_info'],
                'mchId'=>$wechat['mch_id'],
                'appId'=>$wechat['miniapp_id']
            ]);

        }else{
            $this->error("提现申请失败");
        }

    }

    /**
     * 获取提现，分润统计
     */
    public function getUserRechargeTotal(){
        $withdraw = \app\api\model\WithdrawOrder::where('user_id',$this->auth->id)->where('status','=',20)->sum('money');
        $commission = \app\api\model\CommissionRecords::where('sale_id',$this->auth->id)->sum('commission_price');
        $this->success("",[
            'withdraw'=>$withdraw,
            'commission'=>$commission
        ]);
    }

    /**
     * 获取提现列表
     */
    public function getWithdrawList(){
        $between = $this->request->post('between/a');
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $where = [];
        if ($between && count($between) == 2) {
            $where['createtime'] = ['between', [strtotime($between[0] . ' 00:00:00'), strtotime($between[1] . ' 23:59:59')]];
        }
        $list = \app\api\model\WithdrawOrder::where('user_id',$this->auth->id)->where($where)->where('status','=',20)->order('id desc')->paginate($limit, false, ['page' => $page]);
        $this->success("",$list);
    }

    /**
     * 获取医院分润统计
     */
    public function getHospitalCommissionTotal(){
        $between = $this->request->post('between/a');
        $where = [];
        if ($between && count($between) == 2) {
            $where['createtime'] = ['between', [strtotime($between[0] . ' 00:00:00'), strtotime($between[1] . ' 23:59:59')]];
        }

        $list = \app\api\model\hospital\Hospital::where('user_id',$this->auth->id)->select();
        foreach ($list as &$item) {
            $item['commission_total'] = \app\api\model\CommissionRecords::where('hospital_id',$item->id)->where('sale_id',$this->auth->id)->where($where)->sum('commission_price');
            $item['commissionInfo'] = \app\api\model\CommissionRecords::where('hospital_id',$item->id)->where('sale_id',$this->auth->id)->where($where)->order('createtime desc')->find();
        }
        $this->success("",$list);
    }

    /**
     * 获取分润列表
     */
    public function getCommissionList(){
        $between = $this->request->post('between/a');
        $hospitalId = $this->request->post('hospital_id');
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $where = [];
        if ($between && count($between) == 2) {
            $where['createtime'] = ['between', [strtotime($between[0] . ' 00:00:00'), strtotime($between[0] . ' 23:59:59')]];
        }
        if ($hospitalId) {
            $where['hospital_id'] = $hospitalId;
            $hospital = \app\api\model\hospital\Hospital::where('id',$hospitalId)->find();
        }
        
        $list = \app\api\model\CommissionRecords::where('sale_id',$this->auth->id)->where($where)->order('createtime desc')->paginate($limit, false, ['page' => $page]);
        $this->success("",[
            'list'=>$list,
            'hospital'=>$hospital ?? null
        ]);
    }

    /**
     * 获取销售排行
     */
    public function getSaleRank(){
        $date = $this->request->post('date');
        $month1 = date('Y-m');
        $between = [];
        if(!$date){
            $month2 = date('Y-m',strtotime('last month'));
            $between = [date('Y-m-01 00:00:00',strtotime('last month')),date('Y-m-t 23:59:59',strtotime('last month'))];
        }else{
            $month2 = date('Y-m',strtotime($date));
            $between =[date('Y-m-01 00:00:00',strtotime($date)),date('Y-m-t 23:59:59',strtotime($date))];
        }
        $rank = \app\api\model\SaleRank::where('date','between',$between)->where('type',($month1 == $month2 ? 20: 10))->where('user_id',$this->auth->id)->find();
        $this->success('',$rank);
    }

    /**
     * 获取销售排行列表
     */
    public function getSaleRankList(){ 
        $date = $this->request->post('date');
        $month1 = date('Y-m');
        $between = [];
        if(!$date){
            $month2 = date('Y-m',strtotime('last month'));
            $between = [date('Y-m-01 00:00:00',strtotime('last month')),date('Y-m-t 23:59:59',strtotime('last month'))];
        }else{
            $month2 = date('Y-m',strtotime($date));
            $between =[date('Y-m-01 00:00:00',strtotime($date)),date('Y-m-t 23:59:59',strtotime($date))];
        }
        $rank = \app\api\model\SaleRank::field('id,user_id,rank')->with(['user'])->where('date','between',$between)->where('type',($month1 == $month2 ? 20: 10))->select();
        $this->success('',$rank);
    }

     /**
     * 获取医生留言

     */
    public function feedbackList()
    { 
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $between = $this->request->post('between/a',[]);

        $model = new \app\api\model\message\MessageBoard();
        $where = [
            'sale_id' => $this->auth->id,
        ];
        if (count($between) > 0) {
            $where['createtime'] = ['between', [
                    strtotime($between[0].' 00:00:00'),
                    strtotime($between[1].' 23:59:59')  
                ]];
        }
        $data = $model::where($where)->with(['messageType'])->order('createtime', 'desc')->paginate($limit, false, ['page' => $page]);
        $this->success('', $data);
    }

    public function getHospitalList(){
        $title = $this->request->post('title','');
        $where = [];
        if($title){
            $where['title'] = ['like','%'.$title.'%'];
        }
        $list = \app\api\model\hospital\Hospital::where('user_id',$this->auth->id)->where($where)->select();
        $this->success('',$list);
    }

    /**
     * 添加医院
     */
    public function registerHospital(){
        $title = $this->request->post('title');
        $phone = $this->request->post('phone');
        $lat = $this->request->post('lat');
        $lng = $this->request->post('lng');
        $address = $this->request->post('address');
        $discount = $this->request->post('discount',10);
        if(!$title){
            $this->error('请填写医院名称');
        }
        if(!$phone){
            $this->error('请填写联系电话');
        }
        if(!$lat || !$lng){
            $this->error('请选择医院位置');
        }
        if(!$address){
            $this->error('请填写医院详细地址');
        }
        $hospital = \app\api\model\hospital\Hospital::where('title',$title)->find();
        if($hospital){
            $this->error('医院已存在');
        }
        $hospital = \app\api\model\hospital\Hospital::save([
            'user_id' => $this->auth->id,
            'title' => $title,
            'phone' => $phone,
            'lat' => $lat,
            'lng' => $lng,
            'address' => $address,
            'discount' => 10,
        ]);
        $this->success('添加成功',$hospital);
    }

    /**
     * 注册医生
     */
    public function registerDoctor(){
        $hospital_id = $this->request->post('hospital_id');
        $nickname = $this->request->post('nickname');
        $mobile = $this->request->post('mobile');
        $idcardnumber = $this->request->post('idcardnumber');
        $avatar = $this->request->post('avatar','');
        $address = $this->request->post('address');
        $birthday = $this->request->post('birthday');

        if(!$hospital_id){
            $this->error('请选择医院');
        }

        if(!$nickname){
            $this->error('请填写姓名');
        }

        if(!$mobile){
            $this->error('请填写手机号');
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            $this->error('手机号格式错误');
        }

        $model = new \app\api\model\User();

        if($model->where('mobile',$mobile)->find()){
            $this->error('手机号已存在');
        }
        $model->role = 30;
        $model->jointime = time();
        $model->hospital_id = $hospital_id;
        $model->nickname = $nickname;
        $model->mobile = $mobile;
        $model->idcardnumber = $idcardnumber;
        $model->avatar = $avatar;
        $model->address = $address;
        $model->birthday = $birthday;
        $model->status = 'normal';
        $model->sale_id = $this->auth->id;
        $model->save();

        $this->success('',$model);
    }

    public function getDoctorList(){
        $title = $this->request->post('title','');
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);

        $model = new \app\api\model\User();
        $where = [
            'sale_id' => $this->auth->id,
            'role' => 30,
        ];
        if($title){
            $where['nickname'] = ['like','%'.$title.'%'];
        }
        $list = $model::where($where)->with(['hospital'])->paginate($limit, false, ['page' => $page]);
        $this->success('',$list);
    }


}